package com.ruby.bigtable.spark;

import java.util.Arrays;
import java.util.List;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import com.google.common.base.Optional;

import scala.Tuple2;

public class WordCountUpdateStateByKey {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("Word Count");
		JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(5));
		JavaReceiverInputDStream<String> lineRdd = jssc.socketTextStream("127.0.0.1", 9999);
		JavaDStream<String> wordRdd = lineRdd.flatMap(new FlatMapFunction<String, String>() {

			private static final long serialVersionUID = 1L;

			public Iterable<String> call(String t) throws Exception {
				// TODO Auto-generated method stub
				return Arrays.asList(t.split(" "));
			}
		});
		JavaPairDStream<String, Integer> wordPair = wordRdd.mapToPair(new PairFunction<String, String, Integer>() {
			private static final long serialVersionUID = 1L;

			public Tuple2<String, Integer> call(String t) throws Exception {
				// TODO Auto-generated method stub
				return new Tuple2<String, Integer>(t, 1);
			}
		});
		
		jssc.checkpoint("hdfs://hadooptest:9000/user/spark/wordCount/checkpoint");

		JavaPairDStream<String, Integer> result = wordPair.updateStateByKey(new Function2<List<Integer>, Optional<Integer>, Optional<Integer>>() {

			private static final long serialVersionUID = 1L;

			public Optional<Integer> call(List<Integer> v1, Optional<Integer> v2) throws Exception {
				Integer OldNum = 0;
				if(v2.isPresent()) {
					OldNum = v2.get();
				}
				for(Integer val : v1) {
					OldNum += val;
				}
				return Optional.of(OldNum);
			}
		});
		
		result.print();
		
		jssc.start();
		jssc.awaitTermination();
		jssc.stop();
	}

}
